import React, {
    useEffect, useReducer, useRef, useState 
} from 'react';
import CommonUtil from '@/platform/commons/utils/common-util';
import Environments from '@/platform/commons/utils/env-util';
import DynamicIcon from '@/platform/components/dynamic-icon/DynamicIcon';
import LeftToolbarType from '@/platform/types/left-toolbar-type';
import PropTypes from 'prop-types';
import logo from '@/assets/platform/img/logo.png';
import defaultAvatarImg from '@/assets/platform/img/default-avatar.png';
import { OverlayScrollbarsComponent } from 'overlayscrollbars-react';
import CustomImg from '@/platform/components/custom-img/CustomImg';
import UserApi from '@/platform/apis/user-api';
import HttpResultUtils from '@/platform/commons/utils/http-result-util';
import {
    Menu, Modal, notification
} from 'antd';
import screenfull from 'screenfull';
import { useHistory, useLocation } from 'react-router';
import SysApi from '@/platform/apis/sys-api';
import SysStorageUtils from '@/platform/commons/utils/sys-storage-util';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import ImgCropperModal from '@/platform/components/img-cropper/ImgCropperModal';
import { navMenuInitialState, navMenuReducer } from '@/platform/reducers/nav-menu-reducer';
import NavMenuContext from '@/platform/contexts/nav-menu-context';
import IndividuationModal from '@/platform/components/individuation/IndividuationModal';
import UpdatePwd from '@/platform/components/update-pwd/UpdatePwd';
import classes from './LeftToolbar.module.less';
import NavMenu from '../nav-menu/NavMenu';




const LeftToolbar:React.FC<LeftToolbarType> = (props) => {
    const showLogo = CommonUtil.toBoolean(Environments.getEvnProp('REACT_APP_ADMIN_SHOW_LOGO'));
    const defaultAvatar = defaultAvatarImg;

    const toolbarLogoRef:any = useRef();
    const toolbarTopListRef:any = useRef();
    const toolbarBottomListRef:any = useRef();
    const history = useHistory();
    const location = useLocation();
    const [originalUserAvatar, setOriginalUserAvatar] = useState(defaultAvatarImg);
    const [userDropdownVisible, setUserDropdownVisible] = useState(false);
    const [imgCropperVisible, setImgCropperVisible] = useState(false);
    const [updatePwdVisible, setUpdatePwdVisible] = useState(false);
    const [fullscreenState, setFullscreenState] = useState(false);
    const [themeVisible, setThemeVisible] = useState(false);

    const [navMenuState, dispatchNavMenuState] = useReducer(navMenuReducer, navMenuInitialState);
    

   
    /**
     * 跳转首页
     */
    const toHome = () => {
        const homeRoute = Environments.getEvnProp('REACT_APP_HOME_ROUTER');
        homeRoute !== location.pathname && history.push(homeRoute);
    };


    

    /**
     * 停止事件冒泡
     */
    const stopPropagation = (event: any) => {
        event.stopPropagation();
        event.preventDefault();
    };

    /**
     * 退出系统
     */
    const exitSys = () => {
        setUserDropdownVisible(false);
        Modal.confirm({
            title: '确认',
            icon: <QuestionCircleOutlined />,
            content: '您确认退出系统吗？',
            onOk() {
                SysApi.exitLogin().then((res:any) => {
                    if (HttpResultUtils.isSuccess(res)) {
                        SysStorageUtils.removeSessionUserInfo();
                        SysStorageUtils.removeSecurityKey();
                        SysStorageUtils.removeSessionUser();
                        history.push(Environments.getEvnProp('REACT_APP_LOGIN_ROUTER'));
                        setTimeout(() => {
                            notification.success({
                                message: '提示',
                                description: res.data.resultMsg
                            });
                        }, 500);
                    } else {
                        HttpResultUtils.failureTipMsg(res);
                    }
                });
            }
        });
    };

    const userDropdownToggle = () => {
        setUserDropdownVisible(!userDropdownVisible);
    }

    const updatePwdVisibleToggle = () => {
        const visible = !updatePwdVisible;
        setUpdatePwdVisible(visible);
        visible && userDropdownToggle();
    }

    const imgCropperVisibleToggle = () => {
        const visible = !imgCropperVisible;
        setImgCropperVisible(visible);
        visible && userDropdownToggle();
    }

    const menuVisibleToggle = () => {
        dispatchNavMenuState();
    }

    const themeVisibleToggle = () => {
        setThemeVisible(!themeVisible);
    }

    /**
     * 全屏切换
     */
    const fullscreenToggle = () => {
        if (!screenfull.isEnabled) {
            notification.error({
                message: '提示',
                description: '您的浏览器不支持全屏！'
            });
            return;
        }
  
        screenfull.toggle().then(() => {
            setFullscreenState(!fullscreenState)
        });
    };

    const imgUpload = (imgData:any) => {
        UserApi.uploadUserAvatarImg(imgData).then((res:any) => {
            if (HttpResultUtils.isSuccess(res)) {
                notification.success({
                    message: '提示',
                    description: '上传头像成功，刷新页面后生效！'
                });
                setImgCropperVisible(false);
            } else {
                HttpResultUtils.failureTipMsg(res);
            }
        });
    };

    /**
     * 初始化
     */
    const init = () => {
        setOriginalUserAvatar(UserApi.previewUserAvatar());
  
        if (screenfull.isEnabled) {
            screenfull.on('change', () => {
                setFullscreenState(screenfull['isFullscreen' as string]);
            });
        }
    };

    /**
     * 计算
     */
    const calcToolbarTopListWidth = () => {
        const subject = new Subject();
        subject.pipe(debounceTime(110)).subscribe(() => {
            const { height } = CommonUtil.getViewport();

            let toolbarTopListHeight = height - CommonUtil.getElementDimensions(toolbarBottomListRef.current).height - 16;
            if (showLogo) {
                toolbarTopListHeight -= CommonUtil.getElementDimensions(toolbarLogoRef.current).height;
            }
    
            toolbarTopListRef.current.style.height = toolbarTopListHeight + 'px';
            subject.unsubscribe();
        });
        subject.next();
    };
    
    /**
     * resize
     */
    const resize = () => {
        calcToolbarTopListWidth();
    };

    const navMenu = () => {
        if (props.fixedNavMenu) {
            return (
                <div className={classes["app-left-toolbar-menu-fixed"]}>
                    <div className={classes["app-left-toolbar-menu-container"]}>
                        <div className={classes["app-left-toolbar-menu-header"]}>
                            <div className={classes["app-left-toolbar-menu-title"]}>
                                <DynamicIcon iconName="MenuOutlined" />
                                <span>菜单</span>
                            </div>
                        </div>
                        <div className={classes["app-left-toolbar-menu-body"]}>
                            <NavMenu treeData={props.menuData} />
                        </div>
                    </div>
                </div>
            )
        } else {
            return (
                <NavMenuContext.Provider value={dispatchNavMenuState}>
                    {
                        navMenuState.visible && (
                            <div
                                className={classes["app-left-toolbar-menu-backdrop"]}
                                onClick={menuVisibleToggle}
                            >
                                <div className={classes["app-left-toolbar-menu-popover"]} onClick={stopPropagation}>
                                    <div className={classes["app-left-toolbar-menu-container"]}>
                                        <div className={classes["app-left-toolbar-menu-header"]}>
                                            <div className={classes["app-left-toolbar-menu-title"]}>
                                                <DynamicIcon iconName="MenuOutlined" />
                                                <span>菜单</span>
                                            </div>
                                            <div className={classes["app-left-toolbar-menu-close"]} onClick={menuVisibleToggle}>
                                                <DynamicIcon iconName="CloseOutlined" />
                                            </div>
                                        </div>
                                        <div className={classes["app-left-toolbar-menu-body"]}>
                                            <NavMenu treeData={props.menuData} />
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                        )
                    }
                </NavMenuContext.Provider>
            )
        }
    }

    useEffect(() => {
        init();
        resize();
        window.addEventListener('resize', resize);

        return () => {
            window.removeEventListener('resize', resize);
        }
    }, [CommonUtil.getViewport().height])

    return (
        <>
            <div className={classes["app-left-toolbar-container"]}>
                <div className={classes["app-left-toolbar-top"]}>
                    {
                        showLogo && (
                            <div className={classes["app-left-toolbar-top-logo"]} ref={toolbarLogoRef}>
                                <img src={logo} alt="logo" />
                            </div>
                        )
                    }

                    <div ref={toolbarTopListRef}>
                        <OverlayScrollbarsComponent
                            options={{
                                scrollbars: {
                                    autoHide: 'leave',
                                    autoHideDelay: 100
                                }
                            }}
                            className={classes["app-left-toolbar-top-list-scroll"]}
                        >
                       
                            {
                                !props.fixedNavMenu && (
                                    <div className={classes["app-left-toolbar-top-item"]} onClick={menuVisibleToggle}>
                                        <DynamicIcon iconName="MenuOutlined" /> 
                                        <span>菜单</span>
                                    </div>
                                )
                            }
                            
                            <div className={classes["app-left-toolbar-top-item"]} onClick={toHome}>
                                <DynamicIcon iconName="HomeOutlined" />
                                <span>首页</span>
                            </div>
                        </OverlayScrollbarsComponent>
                    </div>
                </div>
                <div className={classes["app-left-toolbar-bottom"]} ref={toolbarBottomListRef}>
                    <div className={classes["app-left-toolbar-bottom-item"]} onClick={fullscreenToggle}>
                        <DynamicIcon iconName={fullscreenState ? 'FullscreenExitOutlined' : 'FullscreenOutlined'} /> 
                        <span>{ fullscreenState ? '取消' : '全屏' }</span>
                    </div>
                    <div className={classes["app-left-toolbar-bottom-item"]} onClick={themeVisibleToggle}>
                        <DynamicIcon iconName="SvgIconTheme" /> 
                        <span>外观</span>
                    </div>
         
                    <div className={classes["app-left-toolbar-bottom-avatar"]} onClick={userDropdownToggle}>
                        <CustomImg imgSrc={originalUserAvatar} errSrc={defaultAvatar} imgAlt="头像" />
                    </div>
                </div>
            </div>

            {
                userDropdownVisible && (
                    <div
                        className={classes["app-left-toolbar-user-dropdown-backdrop"]}
                        onClick={userDropdownToggle}
                    >
                        <div className={classes["app-left-toolbar-user-dropdown-popover"]} onClick={stopPropagation}>
                            <Menu>
                                <Menu.Item onClick={imgCropperVisibleToggle}>
                                    <a>
                                        <DynamicIcon iconName="UploadOutlined" /> 
                                        头像上传
                                    </a>
                                </Menu.Item>
                                <Menu.Item onClick={updatePwdVisibleToggle}>
                                    <a>
                                        <DynamicIcon iconName="LockOutlined" /> 
                                        修改密码
                                    </a>
                                </Menu.Item>
                                <Menu.Item onClick={exitSys}>
                                    <a>
                                        <DynamicIcon iconName="LoginOutlined" /> 
                                        退出系统
                                    </a>
                                </Menu.Item>
                            </Menu>
                        </div>
                    </div>
                )
            }

            {
                navMenu()
            }

            {
                imgCropperVisible && (
                    <ImgCropperModal previewTitle="头像预览" originalImgLabel="原头像" originalImgSrc={originalUserAvatar} onCancel={imgCropperVisibleToggle} onUpload={imgUpload} />
                )
            }

            {

                themeVisible && (
                    <IndividuationModal onCancel={themeVisibleToggle} />
                )
            }

            {
                updatePwdVisible && (
                    <UpdatePwd onCancel={updatePwdVisibleToggle} />
                )
            }

        </>
    ) 
};

LeftToolbar.defaultProps = {
    fixedNavMenu: false 
}

LeftToolbar.propTypes = {
    userData: PropTypes.object.isRequired,
    menuData: PropTypes.array.isRequired,
    fixedNavMenu: PropTypes.bool
}

export default LeftToolbar;
